package cn.lxh.org.service.impl;

import cn.lxh.basic.service.impl.BaseServieceImpl;
import cn.lxh.basic.utils.PageList;
import cn.lxh.org.domain.Department;
import cn.lxh.org.mapper.DepartmentMapper;
import cn.lxh.org.query.DepartmentQuery;
import cn.lxh.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServieceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


/*sd*//*sadasd大发*/
/*sd*/
    @Override
    public List<Department> queryTree() {
//        *  方案四：
//        *    1.一次性查询出所有数据，放到内存 all
        List<Department> departments = departmentMapper.findAll();
        //为了后面找自己的父亲，我们这里可以把整体的部门数据，转换一份成Map<id,department>
        //Map<Long, Department> allDepts = departments.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
        Map<Long, Department> allDepts = new HashMap<>();
        for (Department department : departments) {
            allDepts.put(department.getId(), department);
        }
        List<Department> firstDepts = new ArrayList<>();//顶级部门
        for (Department tmp : departments) {
            if(tmp.getParent_id() == null){
//        *    2.从所有数据中找出第一层级 firstDepts   我们需要返回的最外数据
                firstDepts.add(tmp);
            }else{
//        *    3.只要不是第一层级的，找自己的上级，并将自己放入上级的children中
                Department parent = allDepts.get(tmp.getParent_id());
                if(parent != null){
                    parent.getChildren().add(tmp);
                }
            }
        }
        return firstDepts;
    }
}





